package com.brite.android.game.action;

import java.util.ArrayList;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.FrameLayout;

import com.brite.android.game.Wellcome;
import com.brite.android.game.menu.MainMenu;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class ChoseCharacterAndMapActivity extends BaseGameActivity {

//	private int CAMERA_WIDTH = 480;
//	private int CAMERA_HEIGHT = 320;
	
	private int CAMERA_WIDTH;
	private int CAMERA_HEIGHT;
	
	private Scene scene;
	
	private Texture bgTexture;
	private TextureRegion bgTextureRegion;
	
	private Texture fireBallTexture;
	private TiledTextureRegion fireBallTextureRegion;
	
	// CHARACTER 
	
	private Texture childrenTexture;
	private TiledTextureRegion childrenTextureRegion;
	
	private Texture girlTexture;
	private TiledTextureRegion girlTextureRegion;
	
	private Texture oldManTexture;
	private TiledTextureRegion oldManTextureRegion;
	
	private Texture robotTexture;
	private TiledTextureRegion robotTextureRegion;
	
	boolean choseCharacter = false;
	String characterFileNameLive = new String();
	String characterFileNameDied = new String();
	
	private String[] charactersLivePath = {"robotLive.png", "oldManLive.png", "girlLive.png", "childrenLive.png"};
	private String[] charactersDiedPath = {"robotDied.png", "oldManDied.png", "girlDied.png", "childrenDied.png"};
	
	private ArrayList<AnimatedSprite> arrListCharacters = new ArrayList<AnimatedSprite>();
	
	// MAP
	
	private Texture map_1_Texture;
	private TiledTextureRegion map_1_TextureRegion;
	
	private Texture map_2_Texture;
	private TiledTextureRegion map_2_TextureRegion;
	
	private Texture map_3_Texture;
	private TiledTextureRegion map_3_TextureRegion;
	
	private Texture map_4_Texture;
	private TiledTextureRegion map_4_TextureRegion;
	
	boolean choseMap = false;
	private String mapFileName = new String();
	
	private String[] mapPath = {"map_1.png", "map_2.png", "map_3.png", "map_4.png"};
	private ArrayList<AnimatedSprite> arrListMaps = new ArrayList<AnimatedSprite>();
	
	SharedPreferences pre;
	
	@Override
	public Engine onLoadEngine() {
		Display display = getWindowManager().getDefaultDisplay();
		CAMERA_WIDTH = display.getWidth();
		CAMERA_HEIGHT = display.getHeight();
		
		Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		EngineOptions eo = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
		eo.setNeedsMusic(true);
		eo.setNeedsSound(true);
		mEngine = new Engine(eo);
		
		return mEngine;
	}

	private void loadCharacterResources(){
		childrenTexture = new Texture(512, 128, TextureOptions.DEFAULT);
		childrenTextureRegion = TextureRegionFactory.createTiledFromAsset(childrenTexture, this, "select_chidren(100x180).png", 0, 0, 2, 1);
		
		girlTexture = new Texture(256, 256, TextureOptions.DEFAULT);
		girlTextureRegion = TextureRegionFactory.createTiledFromAsset(girlTexture, this, "select_girl_2.png", 0, 0, 2, 1);
		
		oldManTexture = new Texture(256, 256, TextureOptions.DEFAULT);
		oldManTextureRegion = TextureRegionFactory.createTiledFromAsset(oldManTexture, this, "select_laogia(100x140).png", 0, 0, 2, 1);
		
		robotTexture = new Texture(512, 256, TextureOptions.DEFAULT);
		robotTextureRegion = TextureRegionFactory.createTiledFromAsset(robotTexture, this, "select_robot(140x70).png", 0, 0, 2, 1);
		
		mEngine.getTextureManager().loadTextures(childrenTexture, girlTexture, oldManTexture, robotTexture);
	}
	
	private void loadMapResources(){
		map_1_Texture = new Texture(512, 256, TextureOptions.DEFAULT);
		map_1_TextureRegion = TextureRegionFactory.createTiledFromAsset(map_1_Texture, this, "select_map_01(100x100).png", 0, 0, 2, 1);
		
		map_2_Texture = new Texture(512, 256, TextureOptions.DEFAULT);
		map_2_TextureRegion = TextureRegionFactory.createTiledFromAsset(map_2_Texture, this, "select_map_02(100x100).png", 0, 0, 2, 1);
		
		map_3_Texture = new Texture(512, 256, TextureOptions.DEFAULT);
		map_3_TextureRegion = TextureRegionFactory.createTiledFromAsset(map_3_Texture, this, "select_map_03(100x100).png", 0, 0, 2, 1);
		
		map_4_Texture = new Texture(512, 256, TextureOptions.DEFAULT);
		map_4_TextureRegion = TextureRegionFactory.createTiledFromAsset(map_4_Texture, this, "select_map_04(100x100).png", 0, 0, 2, 1);
		
		mEngine.getTextureManager().loadTextures(map_1_Texture, map_2_Texture, map_3_Texture, map_4_Texture);
	}
	
	@Override
	public void onLoadResources() {
		TextureRegionFactory.setAssetBasePath("gfx/");
		
		bgTexture = new Texture(1024, 1024, TextureOptions.DEFAULT);
		bgTextureRegion = TextureRegionFactory.createFromAsset(bgTexture, this, "menu_game_2.png", 0, 0);

		fireBallTexture = new Texture(512, 256, TextureOptions.DEFAULT);
		fireBallTextureRegion = TextureRegionFactory.createTiledFromAsset(fireBallTexture, this, "fireball_(220x100)_ST.png", 0, 0, 2, 1);
		
		loadCharacterResources();
		loadMapResources();
		
		mEngine.getTextureManager().loadTextures(bgTexture, fireBallTexture);
		
	}
	
	private void loadCharacters(){
		final AnimatedSprite oldManAnimateSprite = new AnimatedSprite(0, 0, oldManTextureRegion);
		oldManAnimateSprite.setPosition(CAMERA_WIDTH/4 + (CAMERA_WIDTH/4 - oldManAnimateSprite.getWidthScaled())/2, CAMERA_HEIGHT/4 + (CAMERA_HEIGHT/4 - oldManAnimateSprite.getHeightScaled())/2);
		scene.attachChild(oldManAnimateSprite);
		
		final AnimatedSprite girlAnimateSprite = new AnimatedSprite(0, 0, girlTextureRegion);
		girlAnimateSprite.setPosition(CAMERA_WIDTH/2 + (CAMERA_WIDTH/4 - girlAnimateSprite.getWidthScaled())/2, CAMERA_HEIGHT/4 + (CAMERA_HEIGHT/4 - girlAnimateSprite.getHeightScaled())/2);
		scene.attachChild(girlAnimateSprite);
		
		AnimatedSprite fireBallAnimatedSprite = new AnimatedSprite(0, 0, fireBallTextureRegion);
		fireBallAnimatedSprite.animate(200);
		fireBallAnimatedSprite.setPosition((CAMERA_WIDTH - fireBallAnimatedSprite.getWidthScaled())/2, (CAMERA_HEIGHT - fireBallAnimatedSprite.getHeightScaled())/2);
		scene.attachChild(fireBallAnimatedSprite);
		
		final AnimatedSprite childrenAnimateSprite = new AnimatedSprite(0, 0, childrenTextureRegion);
		childrenAnimateSprite.setPosition(CAMERA_WIDTH/2 + (CAMERA_WIDTH/2 - childrenAnimateSprite.getWidthScaled())/2, CAMERA_HEIGHT/2 + (CAMERA_HEIGHT/4 - childrenAnimateSprite.getHeightScaled())/2);
		scene.attachChild(childrenAnimateSprite);
		
		final AnimatedSprite robotAnimateSprite = new AnimatedSprite(0, 0, robotTextureRegion);
		robotAnimateSprite.setPosition((CAMERA_WIDTH/2 - robotAnimateSprite.getWidthScaled())/2, CAMERA_HEIGHT/2 + (CAMERA_HEIGHT/4 - robotAnimateSprite.getHeightScaled())/2);
		scene.attachChild(robotAnimateSprite);
		
		arrListCharacters.add(robotAnimateSprite);
		arrListCharacters.add(oldManAnimateSprite);
		arrListCharacters.add(girlAnimateSprite);
		arrListCharacters.add(childrenAnimateSprite);
	}
	
	private void loadMap(){
		final AnimatedSprite map_1_AnimateSprite = new AnimatedSprite(0, 0, map_1_TextureRegion);
		map_1_AnimateSprite.setPosition((CAMERA_WIDTH/4 - map_1_AnimateSprite.getWidthScaled())/2, CAMERA_HEIGHT/4 + (CAMERA_HEIGHT/4 - map_1_AnimateSprite.getHeightScaled())/2);
		map_1_AnimateSprite.setVisible(false);
		scene.attachChild(map_1_AnimateSprite);
		
		final AnimatedSprite map_2_AnimateSprite = new AnimatedSprite(0, 0, map_2_TextureRegion);
		map_2_AnimateSprite.setPosition(CAMERA_WIDTH/4 + (CAMERA_WIDTH/4 - map_2_AnimateSprite.getWidthScaled())/2, (CAMERA_HEIGHT/4 - map_2_AnimateSprite.getHeightScaled())/2);
		map_2_AnimateSprite.setVisible(false);
		scene.attachChild(map_2_AnimateSprite);
		
		final AnimatedSprite map_3_AnimateSprite = new AnimatedSprite(0, 0, map_3_TextureRegion);
		map_3_AnimateSprite.setPosition(CAMERA_WIDTH/2 + (CAMERA_WIDTH/4 - map_3_AnimateSprite.getWidthScaled())/2, (CAMERA_HEIGHT/4 - map_3_AnimateSprite.getHeightScaled())/2);
		map_3_AnimateSprite.setVisible(false);
		scene.attachChild(map_3_AnimateSprite);
		
		final AnimatedSprite map_4_AnimateSprite = new AnimatedSprite(0, 0, map_4_TextureRegion);
		map_4_AnimateSprite.setPosition(3*CAMERA_WIDTH/4 + (CAMERA_WIDTH/4 - map_4_AnimateSprite.getWidthScaled())/2, CAMERA_HEIGHT/4 + (CAMERA_HEIGHT/4 - map_4_AnimateSprite.getHeightScaled())/2);
		map_4_AnimateSprite.setVisible(false);
		scene.attachChild(map_4_AnimateSprite);
		
		arrListMaps.add(map_1_AnimateSprite);
		arrListMaps.add(map_2_AnimateSprite);
		arrListMaps.add(map_3_AnimateSprite);
		arrListMaps.add(map_4_AnimateSprite);
	}
	
	@Override
	public Scene onLoadScene() {
		scene = new Scene(1);
		Sprite bgSprite = new Sprite(0, 0, bgTextureRegion);
		bgSprite.setWidth(CAMERA_WIDTH);
		bgSprite.setHeight(CAMERA_HEIGHT);
		scene.attachChild(bgSprite);
		
//		Log.w("CAMERA_WIDTH : CAMERA_HEIGHT", CAMERA_WIDTH +" : "+ CAMERA_HEIGHT);
		
		loadCharacters();
		
		loadMap();
		
//		scene.registerUpdateHandler(new IUpdateHandler() {
//			
//			@Override
//			public void reset() {
//				
//			}
//			
//			@Override
//			public void onUpdate(float pSecondsElapsed) {
//				if (choseCharacter) {
//					if (!timeToActive.currentStatus()) {
//						startActivity(new Intent(getBaseContext(), MainGame.class));
//						finish();
//					}else {
//						timeToActive.update(pSecondsElapsed);
//					}
//				}
//				
//			}
//		});
		
		scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
			
			@Override
			public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
				
//				Log.w("ClickX : ClickY", pSceneTouchEvent.getX() +" : "+ pSceneTouchEvent.getY());
				
				for (int i = 0; i < arrListCharacters.size(); i++) {
					AnimatedSprite characterSprite = arrListCharacters.get(i);
					
					Region characterRegion = new Region(characterSprite.getX(), characterSprite.getY(), characterSprite.getWidthScaled(), characterSprite.getHeightScaled());
					if (characterRegion.isCovered(new Cordinate(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()), characterRegion)) {
						characterSprite.setCurrentTileIndex(1);
						for (int j = 0; j < arrListCharacters.size(); j++) {
							if (j != i) {
								arrListCharacters.get(j).setCurrentTileIndex(0);
							}
						}
						characterFileNameLive = charactersLivePath[i];
						characterFileNameDied = charactersDiedPath[i];
						choseCharacter = true;
						break;
					}
				}
				
				if (choseCharacter) {
					for (int i = 0; i < arrListMaps.size(); i++) {
						AnimatedSprite mapSprite = arrListMaps.get(i);
						mapSprite.setVisible(true);
						
						Region mapRegion = new Region(mapSprite.getX(), mapSprite.getY(), mapSprite.getWidthScaled(), mapSprite.getHeightScaled());
						if (pSceneTouchEvent.isActionDown() && mapRegion.isCovered(new Cordinate(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()), mapRegion)) {
							mapSprite.setCurrentTileIndex(1);
							for (int j = 0; j < arrListMaps.size(); j++) {
								if (j != i) {
									arrListMaps.get(j).setCurrentTileIndex(0);
								}
							}
							mapFileName = mapPath[i];
							choseMap = true;
							break;
						}
					}
				}else{
					for (int i = 0; i < arrListMaps.size(); i++) {
						arrListMaps.get(i).setVisible(false);
					}
					choseMap = false;
				}
				
				if (choseCharacter && choseMap) {
					writePre(characterFileNameLive, characterFileNameDied, mapFileName);
				}
				
				return false;
			}
		});
		
		return scene;
	}

	@Override
	public void onLoadComplete() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(new Intent(this, MainMenu.class));
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void writePre(String characterName, String characterDied, String mapName){
		pre = getSharedPreferences(Wellcome.PREFS_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = pre.edit();
		editor.putString("CharacterName", characterName);
		editor.putString("CharacterDied", characterDied);
		editor.putString("MapName", mapName);
		editor.commit();
		finish();
		choseCharacter = false;
		choseMap = false;
		startActivity(new Intent(this, MainGame.class));
	}
	
	
	@Override
    protected void onSetContentView() {
        final FrameLayout frameLayout = new FrameLayout(this);
        final FrameLayout.LayoutParams frameLayoutLayoutParams =
                new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
                                             FrameLayout.LayoutParams.FILL_PARENT);
 
        final AdView adView = new AdView(this, AdSize.IAB_BANNER, "a14fbdf32995e3c");
        adView.refreshDrawableState();
        adView.setVisibility(AdView.VISIBLE);
        final FrameLayout.LayoutParams adViewLayoutParams =
                new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
                                             FrameLayout.LayoutParams.WRAP_CONTENT,
                                             Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
        // getHeight returns 0
        // http://groups.google.com/group/admob-pu ... a874df3472
        int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50,
                getResources ().getDisplayMetrics ());
        // top of AD is at middle of the screen
//        adViewLayoutParams.topMargin = height/2;
//        adViewLayoutParams.topMargin = 0;
        Log.v("Add H", "Adview height : " + height);
        Log.v("Add S", "Adview size {x:" + adView.getWidth() + ", y: " + adView.getHeight()+ "}");
 
        AdRequest adRequest = new AdRequest();
        adRequest.setTesting(true);
        adView.loadAd(adRequest);
        if (adView.isReady()) {
        	Log.v("Add S", "Adview size {x:" + adView.getWidth() + ", y: " + adView.getHeight()+ "}");
		}
        adView.setPadding(0, 0, 0, CAMERA_HEIGHT - adView.getHeight() - 60);
        
        this.mRenderSurfaceView = new RenderSurfaceView(this);
        mRenderSurfaceView.setRenderer(mEngine);
 
        final android.widget.FrameLayout.LayoutParams surfaceViewLayoutParams =
                new FrameLayout.LayoutParams(super.createSurfaceViewLayoutParams());
 
        frameLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);
        frameLayout.addView(adView, adViewLayoutParams);
 
        this.setContentView(frameLayout, frameLayoutLayoutParams);
    }
	
}
